package com.study.web.nv;

import com.study.config.BloomFilterHelper;
import com.study.utils.Constant;
import com.study.web.nv.bean.NsSingle;
import com.study.web.nv.bean.thread.NsRunnable;
import com.study.web.nv.service.RedisBloomFilter;
import com.study.web.nv.util.ParseNs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2020/8/9 8:15
 */
@Slf4j
@RestController
//@JsonIgnoreProperties
@RequestMapping("mzt/ns")
@Api(tags = "MZT/ns")
public class Controller {

    //元素ID|该图集包含70张照片
    private static final String id_single_page_num = "dinfo";
    //<ul id="hgallery"><img src="https://img.onvshen.com:85/gallery/22162/32819/s/0.jpg" alt="[XIUREN] 2020.05.13 杨晨晨sugar_0"
    public static final String id_single_page_url = "hgallery";

    public static final String testImgUrl = "https://img.onvshen.com:85/gallery/22162/32819/s/0.jpg";

    //图片名是 005.jpg|是三位数字，不够补充0
    public static final String num_format = "%03d";

    private static final String basePah = "/nvshens/";

    @Value("${sys.config.pic.savepath}")
    private String savePath;

    @Resource(name = "nvshensThreadPool")
    private ExecutorService nvshensThreadPool;


    /****************************************************************************
     *              布隆过滤器添加测试
     *
     */


    @Autowired
    RedisBloomFilter redisBloomFilter;

    @Autowired
    private BloomFilterHelper bloomFilterHelper;

    @ResponseBody
    @GetMapping("/add")
    public String addBloomFilter(@RequestParam("orderNum") String orderNum) {
        try {
            redisBloomFilter.addByBloomFilter(bloomFilterHelper, Constant.KEY_OF_BLOOM, orderNum);
        } catch (Exception e) {
            e.printStackTrace();
            return "添加失败";
        }

        return "添加成功";
    }

    @ResponseBody
    @GetMapping("/check")
    public boolean checkBloomFilter(@RequestParam("orderNum") String orderNum) {

        boolean b = redisBloomFilter.includeByBloomFilter(bloomFilterHelper, Constant.KEY_OF_BLOOM, orderNum);

        return b;
    }

    /****************************************************************************/

    /**
     * 下载详情页 https://www.nvshens.org/g/33205/
     *
     * @param bean
     * @param pageUrl
     * @throws IOException
     */
    void parse(NsSingle bean, String pageUrl) throws IOException {
        Document root = Jsoup.connect(pageUrl).timeout((int) TimeUnit.SECONDS.toMillis(50)).get();
        Elements numSpan = root.getElementById(id_single_page_num).getElementsByTag("span");
        bean.setNum(Integer.parseInt(
                StringUtils.getDigits(numSpan.text())
        ));

        bean.setPageUrl(pageUrl);

        Element eleOfImg = root.getElementById(id_single_page_url).getAllElements().get(0);
        String imgSrc = eleOfImg.child(0).attr("src");

        bean.setExtName(StringUtils.join(".", FilenameUtils.getExtension(imgSrc)));
        bean.setPicUrl(
                StringUtils.join(FilenameUtils.getFullPath(imgSrc),
                        num_format, ".",
                        FilenameUtils.getExtension(imgSrc)));
        if (pageUrl.endsWith("/")) {
            //为了去除最后一个空格，从而提起名字
            pageUrl = StringUtils.substring(pageUrl, 0, pageUrl.length() - 1);
        }
        bean.setSavePath(FilenameUtils.getBaseName(pageUrl));
    }


    @GetMapping("album")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "图集", defaultValue = "https://www.nvshens.org/girl/27717/"),
            @ApiImplicitParam(name = "base", value = "网站baseurl", defaultValue = "https://www.nvshens.org")
    })
    public String album(@RequestParam(defaultValue = "https://www.nvshens.org/girl/27717/") String url,
                        @RequestParam(defaultValue = "https://www.nvshens.org") String base) {
        List<String> album = ParseNs.parseAlbum(url, base);

        log.info("图集{}{}", base, album);
        for (String page : album) {
            String digits = StringUtils.getDigits(page);
            if (redisBloomFilter.includeByBloomFilter(bloomFilterHelper, Constant.KEY_OF_BLOOM, digits)) {
                log.error("已经存在了{}", page);
                continue;
            }
            log.info("图集不存在，开始下载");
            NsSingle nsSingle = new NsSingle();
            try {
                parse(nsSingle, StringUtils.join(base, page));
                redisBloomFilter.addByBloomFilter(bloomFilterHelper, Constant.KEY_OF_BLOOM, digits);

            } catch (IOException e) {
                e.printStackTrace();
            }
            nvshensThreadPool.submit(new NsRunnable(nsSingle, StringUtils.join(savePath, basePah)));
        }

        return LocalDateTime.now().toString();
    }

    /**
     * https://blog.csdn.net/yuguiyang1990/article/details/11488943
     *
     * @param url
     * @return
     */
    @SneakyThrows
    @GetMapping("")
    public String downPic(String url) {

        NsSingle nsSingle = new NsSingle();
        parse(nsSingle, url);
        nvshensThreadPool.submit(new NsRunnable(nsSingle, StringUtils.join(savePath, basePah)));
        return LocalDateTime.now().toString();
    }

    public static void main(String[] args) throws IOException {
        System.out.println(FilenameUtils.getFullPath(testImgUrl));
        String url = "https://www.nvshens.org/g/33438/";
        System.out.println(FilenameUtils.getBaseName(url));
        System.out.println(FilenameUtils.getName(url));

        System.out.println(StringUtils.substring(url, 0, url.length() - 1));
        String.format("%03d", 5);

        //

        String.format("https://t1.onvshen.com:85/gallery/15712/33421/s/%03d.jpg", 5);


        String downUrl = "https://t1.onvshen.com:85/gallery/15712/33421/s/002.jpg";
        Connection.Response response = Jsoup.connect(downUrl).timeout((int) TimeUnit.SECONDS.toMillis(50))
                .referrer("https://www.nvshens.org/girl/23100/album/")
                .ignoreContentType(Boolean.TRUE).execute();
        BufferedInputStream inputStream = response.bodyStream();


    }

    /**
     * 字符串格式化|String.format|https://www.iteye.com/blog/kgd1120-1293633
     */

    void parseSingleUrl(String imgPageUrl) {

        try {
            Document document = Jsoup.connect(imgPageUrl).get();


        } catch (IOException e) {
            e.printStackTrace();
            log.error("解析失败{]", imgPageUrl);
        }

    }


}
